package org.ichow.question.plugins
{
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.events.IEventDispatcher;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	
	/**
	 * ...
	 * 拖动题
	 * @author M.ichow
	 */
	public class DrawInPlugin extends ChoicePlugin
	{
		public static const VERSION:Number = 1.0;
		public static const API:Number = 1.0;
		
		protected var hits : Vector.<DisplayObject>;
		protected var hitedAry : Array;
		protected var hitName : String = "h_$_mc";
		protected var points : Vector.<Point>;
		protected var currentChoice : MovieClip;
		
		public function DrawInPlugin()
		{
			this.propName = "DrawInPlugin";
		}
		
		override protected function init() : void
		{
			super.init();
			hits = new Vector.<DisplayObject>();
			points = new Vector.<Point>();
			hitedAry = [];
			for ( var i : int = 0 ; i < options ; i++ )
			{
				var n : String = hitName.replace( "$" , i );
				hits.push( getChild( n ) );
				points.push( new Point( choices[ i ].x , choices[ i ].y ) );
			}
		}
		
		private function onChoicesUp( e : MouseEvent ) : void
		{
			var index : int = getIndex( currentChoice.name );
			currentChoice.stopDrag();
			currentChoice.stage.removeEventListener( MouseEvent.MOUSE_UP , onChoicesUp );
			//check hit
			for each ( var i : DisplayObject in hits )
			{
				if ( i.hitTestObject( currentChoice ) )
				{
					hitedAry[ getIndex( i.name ) ] = index;
					break;
				}
			}
			currentChoice = null;
			//
			for ( var j : int = 0 ; j < choices.length ; j++ )
			{
				var m : int = hitedAry.indexOf( getIndex( choices[ j ].name ) );
				if ( m != -1 )
				{
					choices[ j ].x = hits[ m ].x;
					choices[ j ].y = hits[ m ].y;
				}
				else
				{
					choices[ j ].x = points[ j ].x;
					choices[ j ].y = points[ j ].y;
				}
			}
		}
		
		override protected function update( mc : MovieClip = null ) : void
		{
			super.update( mc );
			mc.stage.addEventListener( MouseEvent.MOUSE_UP , onChoicesUp );
			mc.startDrag();
			skin.addChild( mc );
			currentChoice = mc;
			if ( hitedAry.indexOf( getIndex( currentChoice.name ) ) != -1 )
			{
				hitedAry[ hitedAry.indexOf( getIndex( currentChoice.name ) ) ] = null;
			}
		}
		
		override public function check() : Boolean
		{
			for ( var i : int = 0 , len : int = answer.length ; i < len ; i++ )
			{
				if ( int( hitedAry[ i ] ) != int( answer[ i ] ) )
				{
					return false;
				}
			}
			return true;
		}
		
		override public function reset() : void
		{
			super.reset();
			hitedAry = [];
			for ( var i : int = 0 , len : int = choices.length ; i < len ; i++ )
			{
				choices[ i ].x = points[ i ].x;
				choices[ i ].y = points[ i ].y;
			}
		}
	
	}

}